package com.gougou.shiro.realm;

import com.gougou.pojo.TbUser;
import com.gougou.service.UserService;
import com.gougou.shiro.token.GougouToken;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 用户权限验证
 * Created by EX-ZHANZHENQIANG001 on 2018-04-27.
 */
public class UserRealm extends AuthorizingRealm{


    @Autowired
    private UserService userService;


    /**
     * 用户登陆认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("用户登陆认证！！！！！");
        //转换token类型
        GougouToken token = (GougouToken) authenticationToken;
        //获取用户名密码
        String principal = token.getuName();
        String credential = token.getpWord();

        //根据用户名从数据库中查询用户的密码（由于操作频繁，这儿建议从redis中查询）
        TbUser tbUser = userService.getUserbyName(principal);
        if(tbUser == null) {
            throw new AccountException("账号或密码不正确！");
        }
        return new SimpleAuthenticationInfo(tbUser, tbUser.getPassword(), this.getName());
    }


    /**
     *  用户权限认证
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //从数据库中获取用户的角色权限

        //获取用户信息
        System.out.println("获取用户权限！");
        return null;
    }


    /**
     * 用户退出登陆，清除缓存
     * @param principals
     */
    @Override
    public void onLogout(PrincipalCollection principals) {
        super.onLogout(principals);
        clearCachedAuthorizationInfo(principals);
    }


}
